import os, os.path

from market.models import UserProfile
from market.chat import chatSettings
from market.chat import xmpp

################################################################################################################
# create a chate user with the name of the bet room (the one the bot will connect with), and initilise the chat room
def createChatRoom( betroomName ):

    # Create the betroom acount. The messages will be sent to the player using this account
    jidStr = chatSettings.CELIBAX_BETROOM_CHAT_ACCOUNT + chatSettings.CHAT_ADDRESS_EXTENSION + '/' + betroomName
    jid = xmpp.protocol.JID( jidStr )
    cli = xmpp.Client( jid.getDomain(), debug=[])
    cli.connect()
    # getRegInfo has a bug that puts the username as a direct child of the
    # IQ, instead of inside the query element.  The below will work, but
    # won't return an error when the user is known, however the register
    # call will return the error.
    xmpp.features.getRegInfo( cli, jid.getDomain(), sync=True)
    if not( xmpp.features.register(
        cli,
        jid.getDomain(),
        {'username':jid.getNode(), 'password': ssettings.CELIBAX_BETROOM_CHAT_PWD } ) ):
        raise Exception('Failed to create a chat room for this bet room')

    
    # create the chat room   
    #http://xmpp.org/extensions/xep-0045.html#createroom
    #http://stackoverflow.com/questions/11338432/how-to-create-muc-in-gtalk-using-python-xmpppy
    cl = xmpp.Client( jid.getDomain(), debug=[] )
    cl.connect()
    cl.auth( jid.getNode(), betroomName )
    presence = xmpp.Presence()
    presence.setFrom( chatSettings.CELIBAX_BETROOM_CHAT_ACCOUNT + chatSettings.CHAT_ADDRESS_EXTENSION + '/' + betroomName )
    presence.setTo( betroomName + chatSettings.CHATROOM_ADDRESS_EXTENSION + '/' + betroomName )
    presence.setTag('x', namespace = 'http://jabber.org/protocol/muc' )
    cl.send( presence )

    
